﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Sansar.Transfer;

namespace BranchOfSansar.Register.Trans
{
    public partial class frmTransPause : BranchOfSansar.Register.Trans.frmTransBase
    {
        
        public frmTransPause()
        {
            InitializeComponent();
        }

        public frmTransPause(long contract_no):this()
        {
            SetContractNo(contract_no);
            frmTransPause_ContractSelected();
        }

        private void txtDescription_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void frmTransPause_ContractSelected()
        {
            pnlTransfer.Enabled = true;
            //Хэрэв урьдчилсан төлбөрт бол
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient tc = new BranchOfSansar.Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                txtProdCode.Properties.ValueMember = "ProdCode";
                txtProdCode.Properties.DisplayMember = "ProdCode";
                txtProdCode.Properties.DataSource = tc.Products("P");
            }
            //if (txtProdCode.Properties
            txtProdCode.ItemIndex = 0;
            
            btnSave.Enabled = true;
            Calc();
        }

        private void frmTransPause_Load(object sender, EventArgs e)
        {
            txtDate.DateTime = DateTime.Now;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {            
            List<Transaction> txn = new List<Transaction>();
            List<SendTransfer> strans = new List<SendTransfer>();
            BranchOfSansar.Sansar.Enquiry.Product p = (BranchOfSansar.Sansar.Enquiry.Product)txtProdCode.Properties.GetDataSourceRowByDisplayValue(txtProdCode.Text);
            if (p == null) return;
            if (Contract.Status == 2)
            {
                Globals.Warr("Гэрээг түр хаасан байна.");
                return;
            }
            
            SendContract con = new SendContract()
            {
                ContractNo = Contract.ContractNo,
                Balance = txtLastBalance.Value,               
                EndDate = Contract.EndDate??txtDate.DateTime,
                StartDate = Contract.StartDate??txtDate.DateTime,                
                Status=2 ,//Түр хаах 
                PauseDate=Globals.GetDate()
            };

            txn.Add(new Transaction()
            {
                ContractNo = Contract.ContractNo,
                ProdCode = p.ProdCode,
                Quantity = 1,
                StartDate = txtDate.DateTime,
                EndDate = null,
                Status = 1,
                TxnCategory = ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbTransCategory.SelectedItem).StrValue,
                BankNo = cmbBank.Enabled ? ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbBank.SelectedItem).IntValue : 0,
                TxnPrice = txtPrice.Value,
                TxnAmount = txtAmount.Value,
                TxnDebtAmount=txtPrice.Value,
                TxnFirstBalance=decimal.Parse(txtBalance.Text),
                TxnDate = txtDate.DateTime,
                TxnDesc = txtDesc.Text.Length>0 ? txtDesc.Text: "Түр хугацаанд хаах",
                TxnType = 1000,
                UserNo = Globals.UserId
            });


            if (Contract.ProdType == "F") //Урдчилан төлбөрт бол?
            {
                using (TransferClient tcc = new TransferClient(Globals.Token))
                {
                    vw_Transaction[] btrans = tcc.TransactionList(string.Format("it.ContractNo={0} AND it.EndDate> DateTime'{1} 00:00'"
                        , Contract.ContractNo, Globals.SystemDate.ToString("yyyy-M-d")));

                    foreach (var t in btrans)
                    {
                        if (t.StartDate < Globals.SystemDate)
                        {
                            var div = (t.EndDate - Globals.SystemDate);
                            int d = div.Value.Days;
                            //Ялгаатай өдрөөр гүйлгээ үүснэ
                            txn[0].Quantity = d;
                            txn.Add(new Transaction()
                            {
                                ContractNo = Contract.ContractNo,
                                ProdCode = t.ProdCode,
                                Quantity = 1,
                                StartDate = Globals.SystemDate,
                                EndDate = t.EndDate,
                                PerTransNo = t.TransNo,
                                Status = 4,
                                TxnCategory = t.TxnCategory,
                                BankNo = t.BankNo,
                                TxnPrice = 0,
                                TxnAmount = 0,
                                TxnDebtAmount = 0,
                                TxnFirstBalance = decimal.Parse(txtBalance.Text),
                                TxnDate = t.TxnDate.AddMinutes(1),
                                TxnDesc = txtDesc.Text + ". Үлдсэн хоног (" + d + ")",
                                TxnType = 1201,
                                UserNo = Globals.UserId
                            });
                            strans.Add(new SendTransfer()
                                {
                                    TransNo = t.TransNo,
                                    EndDate = Globals.SystemDate,
                                    //Status = 4
                                });
                        }
                        else //Түр хааж идэвхгүй төлөвт оруулах
                            strans.Add(new SendTransfer()
                                {
                                    TransNo = t.TransNo,
                                    Status = 4
                                });

                    }

                }
            }
            else //Дараа төлбөрт
            {
                con.BalanceDate = Globals.SystemDate;                
            }

            using (TransferClient tc = new TransferClient(Globals.Token))
            {
                var res = tc.DoTransaction(txn.ToArray(),strans.ToArray(), con);
                if (res.Code != 0)
                    Globals.Warr(res.Message);
                else
                {
                    Globals.Info(res.Message);
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
            btnSave.Enabled = false;
        }

        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
      
        private void txtAmount_EditValueChanged(object sender, EventArgs e)
        {
            Calc();
        }

        private void Calc()
        {
            decimal first = decimal.Parse(string.IsNullOrEmpty(txtBalance.Text) ? "0" : txtBalance.Text);
            txtLastBalance.Value = first + txtPrice.Value - txtAmount.Value;
        }

        private void txtProdCode_EditValueChanged(object sender, EventArgs e)
        {
            using (BranchOfSansar.Sansar.Transfer.TransferClient tr = new Sansar.Transfer.TransferClient(Globals.Token))
            {
                BranchOfSansar.Sansar.Enquiry.Product p = (BranchOfSansar.Sansar.Enquiry.Product)txtProdCode.Properties.GetDataSourceRowByDisplayValue(txtProdCode.Text);
                txtPrice.Text = p.Price.ToString("#,##0");
                txtProdDescription.Text = string.Format("{0}, {1}, {2} сар", p.Name, p.ProdType == "L" ? "Дараа" : "Урьдчилсан", p.Length);
            }
        }
    }
}
